package com.study.test;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @version V1.0
 * @title: PhantomJsUtil
 * @description: ${DESCRIPTION}
 * @author: wanghuilong
 * @date: 2019-04-26 17:18
 * @copyright: http://fingo.com.my/
 */
public class PhantomJsUtil {

    public static String getPage(String url, String jsFile) {
        StringBuffer error = new StringBuffer();
        StringBuffer resultStr = new StringBuffer();
        try {
            if (null == jsFile) {
                jsFile = "/Users/fingo/Desktop/work_dir/lib/phantom.js";
            }
            Runtime rn = Runtime.getRuntime();
            Process process = rn.exec("phantomjs " + jsFile + " " + url);

            BufferedReader errorRead = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String temp = "";
            while ((temp = errorRead.readLine()) != null) {
                error.append(temp);
                System.out.println(temp);
            }

            InputStream inputStream = process.getInputStream();

            BufferedReader result = new BufferedReader(new InputStreamReader(inputStream));
            while ((temp = result.readLine()) != null) {
                resultStr.append(temp);
                System.out.println(temp);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error.toString();
        }
        return resultStr.toString();
    }

}
